/*
 * FileName：PayCtrl.java 
 * <p>
 * Copyright (c) 2017-2020 <a href="">hermit(1154808491@qq.com)</a>.
 * <p>
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl-3.0.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package com.koine.admin.sys.ctrl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.jpay.alipay.AliPayApi;
import com.jpay.ext.kit.PaymentKit;
import com.jpay.ext.kit.StrKit;
import com.jpay.ext.kit.ZxingKit;
import com.jpay.util.StringUtils;
import com.jpay.weixin.api.WxPayApi;
import com.jpay.weixin.api.WxPayApiConfig;
import com.jpay.weixin.api.WxPayApiConfigKit;
import com.koine.common.BaseCtrl;
import com.koine.common.util.AjaxResult;
import com.koine.common.util.PropertiesUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @author hermit
 * @version 2.0
 * @date 2018-04-17 10:54:58
 */
@Controller
@RequestMapping("pay")
public class PayCtrl extends BaseCtrl {

    @ResponseBody
    @RequestMapping(value = "/wxpay")
    public AjaxResult wx(String total)
            throws Exception {
        total="520";
        Map<String, String> params = WxPayApiConfigKit.getWxPayApiConfig()
                .setAttach("IJPay 测试  -By Javen")
                .setBody("IJPay 扫码支付2测试  -By Javen")
                .setSpbillCreateIp("127.0.0.1")
                .setTotalFee(total)
                .setTradeType(WxPayApi.TradeType.NATIVE)
                .setNotifyUrl("127.0.0.1")
                .setOutTradeNo(String.valueOf(System.currentTimeMillis()))
                .build();

        String xmlResult = WxPayApi.pushOrder(false, params);

        Map<String, String> resultMap = PaymentKit.xmlToMap(xmlResult);

        String return_code = resultMap.get("return_code");
        String return_msg = resultMap.get("return_msg");
        if (!PaymentKit.codeIsOK(return_code)) {
            return AjaxResult.failure(return_msg);
        }
        String result_code = resultMap.get("result_code");
        if (!PaymentKit.codeIsOK(result_code)) {
            return AjaxResult.failure(return_msg);
        }
        //生成预付订单success
        String qrCodeUrl = resultMap.get("code_url");
//        String name = "payQRCode2.png";
        ZxingKit.encodeOutPutSteam(response.getOutputStream(), qrCodeUrl, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200);

//        Boolean encode = ZxingKit.encode(qrCodeUrl, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200,
//                request.getServletContext().getRealPath("/")+File.separator+name);
//        if (encode) {
//            return AjaxResult.success(qrCodeUrl);
//        }
        return null;
    }

    /**
     * 生成支付二维码（模式一）并在页面上显示
     */
    @RequestMapping(value = "/scanCode1", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxResult scanCode1() throws Exception {
        String product_id=String.valueOf(System.currentTimeMillis());
        if (StrKit.isBlank(product_id)) {
            return AjaxResult.failure();
        }
        WxPayApiConfig config = WxPayApiConfigKit.getWxPayApiConfig();
        //获取扫码支付（模式一）url

        String qrCodeUrl = WxPayApi.getCodeUrl(config.getAppId(), config.getMchId(), product_id, config.getPaternerKey(), true);
        //生成二维码保存的路径

        ZxingKit.encodeOutPutSteam(response.getOutputStream(), qrCodeUrl, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200);

        return null;
    }

    /**
     * 扫码支付
     */
    @RequestMapping(value ="/tradePrecreatePay")
    @ResponseBody
    public AjaxResult tradePrecreatePay(String totalAmount) {
        String subject = "Javen 支付宝扫码支付测试";
//        String totalAmount = "86";
        String storeId = "123";
        String notifyUrl = PropertiesUtil.getString("alipay.notifyUrl");

        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setSubject(subject);
        model.setTotalAmount(totalAmount);
        model.setStoreId(storeId);
        model.setTimeoutExpress("5m");
        model.setOutTradeNo(StringUtils.getOutTradeNo());
        try {
            String resultStr = AliPayApi.tradePrecreatePay(model, notifyUrl);
            JSONObject jsonObject = JSONObject.parseObject(resultStr);
            String qrCodeUrl = jsonObject.getJSONObject("alipay_trade_precreate_response").getString("qr_code");
            ZxingKit.encodeOutPutSteam(response.getOutputStream(), qrCodeUrl, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
